const http = require('http')
const fs = require('fs')
const md5 = require('md5-node')

const port = 8383
const JS_LAST_MODIFIED = new Date().toLocaleString()

http.createServer((request, response) => {
  console.log(request.url)
  if (request.url === '' || request.url === '/' || request.url === '/index.html') {
    fs.readFile('./index.html', 'utf-8', (error, data) => {
      if (!error) {
        // 浏览器设置的缓存响应头.
        // 对于主页设置缓存无效.
        response.setHeader('Cache-Control', "private,max-age=31536000")
        response.setHeader("Content-Type", "text/html");
        // response.writeHead('200','OK')
        console.log(new Date().toLocaleString())
        response.end(data)
      } else {
        response.end('错误了')

      }
    })
  } else if (request.url.includes('img')) {
    // 给图片设置 cache-control:max-age=100 ,让浏览器换成此图片100s
    fs.readFile('./img.jpg', (err, file) => {
      // 给图片设置缓存强制缓存 cache-control
      response.setHeader('Cache-Control', 'max-age=100')
      response.setHeader('Content-type', 'image/jpg')
      response.end(file)
    })
  } else if (request.url.endsWith('.js')) {
    // 对比缓存之 Last-Modified & If-Modified-Since
    // 服务器设置 Last-Modified 告知客户端最后修改时间.
    // 客户端每次请求服务器时,服务器利用 If-Modified-Since 和 Last-Modified 对比
    // 如果时间对比相同,说明文件没有修改.字节返回header头,并设置304.Not Modified
    // 否则就把最新的文件返回,200 OK
    console.log(JS_LAST_MODIFIED)
    console.log(request.headers['if-modified-since'])
    if (request.headers['if-modified-since'] === JS_LAST_MODIFIED) {
      // 如果相同,说明资源没有被修改,直接返回304 Not Modified
      response.writeHead('304','Not Modified')
      response.end()
    } else {
      // 否则资源被修改了,重新设置 Last-Modified 并重新返回新的资源数据
      response.setHeader('Last-Modified', JS_LAST_MODIFIED)
      fs.readFile('./vue.js', (err, file) => {
        response.end(file)
      })
    }
  } else if (request.url.endsWith('.css')) {
    // If-None-Match & ETag
    // 每次都要编码一下.
    const etag = md5('hello world')
    console.log(`服务器etag`, etag)
    console.log(`请求的if-none-match;${request.headers['if-none-match']}`)
    console.log(etag === request.headers['if-none-match'])
    if (request.headers['if-none-match'] === etag) {
      response.writeHead(304)
      response.end()
    } else {
      fs.readFile('./css.css', (err, file) => {
        response.setHeader('Etag', etag)
        response.write(file)
        response.end()
      })
    }
  }





}).listen(port, (err) => {
  if (!err) {
    console.log(`server is runing at ${port}`)
  }
})